{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d9ae1109-9753-4e8e-bc15-ff848d463dc3",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "from langchain import hub\n",
    "from langchain.agents import load_tools\n",
    "from langchain.agents import create_openai_functions_agent #不同的agent有不同的创建方式\n",
    "from langchain.agents import AgentExecutor\n",
    "#创建LLM \n",
    "llm = ChatOpenAI(model_name=\"gpt-4\", temperature=0)\n",
    "#定义agent的prompt\n",
    "#https://smith.langchain.com/hub/hwchase17/openai-functions-agent\n",
    "prompt = hub.pull(\"hwchase17/openai-functions-agent\")\n",
    "#定义工具,加载预制的工具,注意有的工具需要提供LLM\n",
    "tools = load_tools([\"llm-math\"], llm=llm)\n",
    "#创建agent\n",
    "agent = create_openai_functions_agent(llm, tools, prompt)\n",
    "#定义agent的执行器，这里注意与老版本的不同\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)\n",
    "agent_executor.invoke({\"input\": \"你好\"})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "90f2682d-b355-44ca-94bc-3214a8f12b55",
   "metadata": {},
   "source": [
    "## Agent\n",
    "- 中间步骤处理\n",
    "- 提示词\n",
    "- 模型配置(停止符必要的话)\n",
    "- 输出解析器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4236a22d-d59b-4a01-a1a6-525b592ba5e2",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain import hub\n",
    "from langchain.agents import AgentExecutor, tool\n",
    "from langchain.agents.output_parsers import XMLAgentOutputParser\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "#配置模型\n",
    "model = ChatOpenAI(\n",
    "    model=\"gpt-4-1106-preview\",\n",
    "    temperature=0,\n",
    "    )\n",
    "\n",
    "#可用工具\n",
    "@tool\n",
    "def search(query: str) -> str:\n",
    "    \"\"\"当需要了解最新的天气信息的时候才会使用这个工具。\"\"\"\n",
    "    return \"晴朗,32摄氏度,无风\"\n",
    "tool_list = [search]\n",
    "tool_list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "21ae3643-a8c7-4dbf-a96b-846875b8bf9a",
   "metadata": {},
   "outputs": [],
   "source": [
    "prompt = hub.pull(\"hwchase17/xml-agent-convo\")\n",
    "prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2c7ce0fd-cbb7-4bec-9686-4ae6e456a801",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python (langchain)",
   "language": "python",
   "name": "langchain-env"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
